package com.qiall.game.gobang.command;

import com.alibaba.fastjson.JSON;
import com.qiall.game.gobang.RoomPool;
import com.qiall.game.gobang.kafka.DataKafkaQueue;
import com.qiall.game.gobang.kafka.Protocol;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 建立链接命令
 * 把
 */
@Component("connectCommandService")
@Slf4j
public class ConnectCommandService implements CommandService {

    @Autowired
    private DataKafkaQueue dataKafkaQueue;

    @Override
    public String getCommand() {
        return CommandEnum.CONNECT.getCode();
    }

    /**
     * 操作 建立连接判断是否有空闲的房间如果有则进入房间 返回对局开始
     */
    @Override
    public void process(Protocol protocol) {
        Integer status = RoomPool.getSessionStatus(protocol.getSessionId());
        if (RoomPool.Room.enter.equals(status)) {
            log.error("session id [{}],状态不是等待状态", protocol.getSessionId());
            return;
        }
        Integer roomId = RoomPool.enterRoom(protocol.getSessionId());
        // 等待中
        if (RoomPool.getWaitRoom().getRoomId().equals(roomId)) {
            return;
        }
        // 发送开始下棋的命令
        sendConnectedMessage(roomId);
        return;
    }

    /**
     * 发送连接成功开始下棋的命令
     * @param roomId
     */
    private void sendConnectedMessage(Integer roomId){
        RoomPool.Room room = RoomPool.getRoom(roomId);
        // to sessionId1
        Protocol protocol1 = new Protocol();
        ReturnData returnData = new ReturnData();
        returnData.setRoomId(roomId);
        returnData.setIsCurrentMoveSession(room.getCurrentMoveSession().equals(room.getSessionId1()));
        String sendData1 = JSON.toJSONString(returnData);
        protocol1.setCommand(CommandEnum.CONNECTED.getCode());
        protocol1.setSessionId(room.getSessionId1());
        protocol1.setData(sendData1);
        dataKafkaQueue.sedSocketMessage(protocol1);
        //to sessionId2
        Protocol protocol2 = new Protocol();
        ReturnData returnData2 = new ReturnData();
        returnData2.setRoomId(roomId);
        returnData2.setIsCurrentMoveSession(room.getCurrentMoveSession().equals(room.getSessionId2()));
        String sendData2 = JSON.toJSONString(returnData2);
        protocol2.setCommand(CommandEnum.CONNECTED.getCode());
        protocol2.setSessionId(room.getSessionId2());
        protocol2.setData(sendData2);
        dataKafkaQueue.sedSocketMessage(protocol2);
    }
    /**
     * 解析data
     */
    @Data
    public static class ConnectData {
        String sessionId;
    }

    @Data
    public static class ReturnData {
        Integer roomId;
        private Boolean isCurrentMoveSession;
    }
}
